import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { getMenuTree } from '@/api/system/menusApi'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};

VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch(err => err);
};



const routes = [
  {path:'/',redirect:'/login'},
  {path:'/login',name:'login',component: ()=> import('@/views/loginAndRegistory/Index.vue')},
  {path:'/register',name:'register',component: ()=> import('@/views/loginAndRegistory/CompanyRegistory.vue')},
  {
    path:'/home',
    name:'home',
    redirect:"/index",
    component: ()=> import('@/views/Home.vue'),
    children:[
      {path: '/index',name:'index',title:{title:'首页'},component: ()=> import('@/views/index.vue')}
    ]},
  {path: '*',name:'404',component: () => import('@/views/404.vue')},
]

const router = new VueRouter({
  routes,
  mode:"history"
})

//设置路由守卫
router.beforeEach((to,from,next) => {
  //放行登录接口
  if(to.path === '/login'){
    return next();
  }
  //校验用户是否登录
  let token = store.getters['user/GET_TOKEN'];
  if(token){
    //加载用户的菜单
    loadLoginUserMenusPromise().then(()=>{
      next();
    })
  }else{
    next('/login');
  }
})

//加载用户菜单转化为动态路由
const loadLoginUserMenus = (callback)=>{
  setTimeout(() => {
    let menus = store.getters['user/GET_MENUS'];
    if(menus.length === 0){
      getMenuTree()
      .then(data => {
        data.unshift({
          name: '首页',
          parentId: 0,
          component:'/index',
          path: '/index',
          icon: 'icon-shouyefill',
          menuType: 'C'
        });  
        store.dispatch('user/UPDATE_MENUS',data);
        let home = routes.find(router=>router.name === 'home');
        //动态增加子路由
        dynamicAddRouter(data,home);
      })
      .catch(err => {
        console.log(err);
      })
    }
  }, 1000);
  callback(true);
}

//将加载用户菜单转化为动态路由 转化为Promise函数
const loadLoginUserMenusPromise = ()=>{
  return new Promise((resolve,reject)=>{
    loadLoginUserMenus((menus)=>{
      resolve(menus)
    })
  })
}


//动态添加路由
const dynamicAddRouter = (menus,toute)=>{
  //菜单不为空才根据菜单加载路由
  if(menus && menus.length > 0){
    //循环添加路由
    menus.forEach(menu=>{
      //如果菜单拥有子菜单向下进行递归
      if(menu.child && menu.child.length >0){
        //递归前先创建当前父路由
        let newRoute = menuToRoute(menu);
        if(newRoute){
          router.addRoute(toute.name,newRoute);
        }
        dynamicAddRouter(menu.child,toute)
      }else{
        //将菜单数据转为路由数据
        let newRoute = menuToRoute(menu);
        if(newRoute){
          //添加路由
          router.addRoute(toute.name,newRoute);
        }
      }
    })
  }
}

//转换菜单为路由
const menuToRoute = (menu) => {
  if(menu.component){
    let newRoute = {
      name: menu.component,
      path: menu.component,
      meta: {
        title: menu.name,
        level: menu.menuType
      },
      component: (resolve) => require(["@/views"+menu.component], resolve)
    }
    return newRoute;
  }else{
    return null;
  }
}

//防止修改项目后路由挂在失败
const initRouters = ()=>{
  let menus = store.getters['user/GET_MENUS'];
  if(menus && menus.length > 0){
    let layoutRouter = routes.find(r=>r.name === 'home');
    dynamicAddRouter(menus,layoutRouter);
  }
}
initRouters();

export {loadLoginUserMenus}
export default router;